package com.harmontronics.hanma.paas.paas.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.harmontronics.hanma.paas.paas.common.MosResponse;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.HmMenu;
import com.harmontronics.hanma.paas.paas.domain.iam.service.HmMenuService;
import com.harmontronics.hanma.paas.paas.domain.iam.service.HmUserGroupManageService;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.ChangePassword;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUser;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUserHigherUpdate;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.HmUserPwd;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SsoOrgResult;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SsoSubmitUserResult;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SsoUserDtoResult;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SsoUserResult;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.SubmitterUser;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.UserMoveOrg;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.UserSort;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserPO;
import com.harmontronics.hanma.paas.paas.domain.organization.service.IHmOrgService;
import com.harmontronics.hanma.paas.paas.domain.organization.service.IHmUserService;
import com.harmontronics.hanma.paas.paas.domain.organization.service.MosService;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.token.MosTokenKit;
import com.harmontronics.hanma.paas.paas.utils.MyBeanUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

@Service("hmUserMosAppService")
@DS("#header.App-Unique")
@ConditionalOnProperty(prefix = "mos.oss",name="enabled",havingValue = "true")
public class HmUserMosAppService implements IHmUserService {

    @Autowired
    private MosService mosService;

    @Autowired
    private MosTokenKit mosTokenKit;

    @Autowired
    private HmMenuService hmMenuService;

    @Autowired
    private HmUserGroupManageService hmUserGroupManageService;

    @Autowired
    private IHmOrgService hmOrgService;

    @Override
    public String login(HmUser userLogin) {
        return null;
    }

    @Override
    public void logout() {
        mosTokenKit.delete();
    }

    @Override
    public HmUser get(Long id) {
        MosResponse<SsoUserDtoResult> userResult = mosService.getUserById(id);
        if(userResult.isOk()){
            SsoUserDtoResult user = userResult.getData();
            if(Optional.ofNullable(user).isPresent()){
                HmUser hmUser = BeanUtil.toBean(user,HmUser.class);
                Long higherid = user.getHigherId();
                MosResponse<SsoOrgResult> orgResult = mosService.getOrgById(higherid);
                if(orgResult.isOk()){
                    SsoOrgResult org = orgResult.getData();
                    if(Optional.ofNullable(org).isPresent()){
                        hmUser.setHigherName(org.getName());
                    }
                }
                return hmUser;
            }
            return null;
        }
        throw new ErrorKeyException(I18nKeyEnum.SYSTEM_ERROR);
    }

    @Override
    public PageBase<HmUser> getPageUserWithParams(int pageNo,int pageSize, Long orgId,
            String name, String jobNumber, Integer status, String email, String mobile,
            String userName) {
            MosResponse<PageBase<SsoUserDtoResult>> userResponse =
                    mosService.getPageUserwithParams(pageNo,pageSize,orgId,name,jobNumber,mobile,status,userName,email);
            if(userResponse.isOk()){
                PageBase<SsoUserDtoResult> pageBase = userResponse.getData();
                PageBase<HmUser> resultPageBase = PageBase.copy(pageBase,HmUser.class);
                return resultPageBase;
            }
            throw new ErrorKeyException(I18nKeyEnum.SYSTEM_ERROR);
    }

    @Override
    public PageBase<HmUserPO> getPageUserWithParams(int pageNo,int pageSize, String searchKey) {
        MosResponse<PageBase<SsoUserResult>> response = mosService.searchUser(searchKey,pageNo,pageSize);
        if(response.isOk()){
            PageBase<SsoUserResult> userPageBase = response.getData();
            PageBase<HmUserPO> resultPageBase = PageBase.copy(userPageBase,HmUserPO.class);
            return resultPageBase;
        }
       return null;
    }

    @Override
    public List<HmUser> getList() {
        return null;
    }


    @Override
    public List<HmMenu> getAuthWithUserId() {
        Long userId = mosTokenKit.getId();
        List<HmMenu> hmMenuList = new ArrayList<>();
        List<HmMenu> resultList = new ArrayList<>();
        MosResponse<SsoUserDtoResult> response = mosService.getUserById(userId);
        SsoUserResult userResult = mosService.mockGetUserById(userId);
        if(response.isOk()){
            SsoUserDtoResult user = response.getData();
            if(Optional.ofNullable(user).isPresent()){
                //如果当前用户是超级管理员
                if (user.getIsSuperAdmin()) {
                    hmMenuList = hmMenuService.getList();
                    return hmMenuList;
                } else {
                    // 1.根据id 获取当前用户所在的组织架构及其父节点
                    List<Long> orgIds = hmOrgService.selectOrgParentIdWithUserId(userId);

                    // 2.从用户组 管理员及成员中获取所在的用户组
                    List<Long> userGroupIds =
                            hmUserGroupManageService.selectGroupIdsWithOrgIdAndUserId(orgIds, userId);

                    // 3.根据用户组获取角色 从角色中获取对应的菜单操作权限
                    List<Long> menuIdList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(userGroupIds)) {
                        menuIdList = hmMenuService.selectMenuIdsWithGroupId(userGroupIds);
                    }

                    List<HmMenu> menuList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(menuIdList)) {
                        hmMenuList = hmMenuService.getMenuWithIds(menuIdList);

                    }
                }
                List<HmMenu> allMenuList = hmMenuService.getList();

                getAuthMenu(allMenuList, hmMenuList, resultList);
                resultList.addAll(hmMenuList);

                resultList = resultList.stream().distinct().collect(Collectors.toList());
                resultList = resultList.stream().sorted(Comparator.comparing(HmMenu::getSerialNum)).collect(
                        Collectors.toList());
            }

        }
        return resultList;

    }

    @Override
    public List<HmUser> getUsersByIds(List<Long> idList) {
        String tmpIds = idList.stream().map(id -> id.toString()).collect(Collectors.joining(","));
        MosResponse<List<SsoUserDtoResult>> response = mosService.listByIds(tmpIds);
        if(response.isOk()){
            List<SsoUserDtoResult> userDtoResultList = response.getData();
            return MyBeanUtils.batchTransform(HmUser.class,userDtoResultList);
        }
        throw new ErrorKeyException(I18nKeyEnum.SYSTEM_ERROR);
    }

    @Override
    public HmUser getUserWithToken() {
        Long userId = mosTokenKit.getId();
        MosResponse<SsoUserDtoResult> response = mosService.getUserById(userId);
        if(response.isOk()){
            SsoUserDtoResult userDtoResult = response.getData();
            return BeanUtil.toBean(userDtoResult,HmUser.class);
        }
        throw new ErrorKeyException(I18nKeyEnum.SYSTEM_ERROR);

    }


    @Override
    public List<SubmitterUser> selectSubmitterUserIn(List<Long> submitterIds) {
        String tmpIds = submitterIds.stream().map(id -> id.toString())
                .collect(Collectors.joining(","));
        MosResponse<List<SsoSubmitUserResult>> response = mosService.getSubmitUser(tmpIds);
        if(response.isOk()){
            List<SsoSubmitUserResult> userResultList = response.getData();
            return MyBeanUtils.batchTransform(SubmitterUser.class,userResultList);
        }

        throw new ErrorKeyException(I18nKeyEnum.SYSTEM_ERROR);

    }

    @Override
    public List<HmUser> findByManageOrg(Long orgId){
        List<HmUser> userPOList = new ArrayList<>();
        MosResponse<List<SsoUserResult>> response = mosService.findUserByOrgId(orgId);
        if(response.isOk()){
            List<SsoUserResult> userResultList = response.getData();
            if(CollectionUtils.isNotEmpty(userResultList)){
                userPOList = MyBeanUtils.batchTransform(HmUser.class,userResultList);
                return userPOList;
            }
        }
        return userPOList;
    }

    private void getAuthMenu(List<HmMenu> allMenuList, List<HmMenu> hmMenuList, List<HmMenu> resultList) {
        List<HmMenu> parentMenuList = new ArrayList<>();

        for (int i = 0; i < allMenuList.size(); i++) {
            Long id = allMenuList.get(i).getId();
            for (int j = 0; j < hmMenuList.size(); j++) {
                if (hmMenuList.get(j).getParentId() != null) {
                    if (hmMenuList.get(j).getParentId().longValue() == id.longValue()) {
                        resultList.add(allMenuList.get(i));
                        parentMenuList.add(allMenuList.get(i));
                    }
                }
            }
        }
        if (parentMenuList.size() > 0) {
            getAuthMenu(allMenuList, parentMenuList, resultList);

        }
    }


    @Override
    public void updateHigher(HmUserHigherUpdate hmUserHigherUpdate) {

    }

    @Override
    public void updatePassword(HmUserPwd hmUserPwd) {

    }

    @Override
    public Long save(HmUser user) {
        return null;
    }

    @Override
    public void update(HmUser user) {

    }

    @Override
    public void remove(List<Long> idList) {

    }

    @Override
    public void moveOrg(UserMoveOrg moveOrgDto) {

    }

    @Override
    public void changePassword(ChangePassword changePasswordInputDto) {

    }

    @Override
    public void resetPassword(List<Long> idList) {

    }

    @Override
    public boolean uniqueCheck(Long id, String field, String value) {
        return false;
    }

    @Override
    public void quit(List<Long> idsList) {

    }


    @Override
    public void userSort(UserSort userSort) {

    }
}
